import logging

from skyfield.api import Loader, utc
from astropy.coordinates import SkyCoord
import astropy.units as u
from skyfield.positionlib import Geocentric
from astro_info import *
from zodiac_info import *
import swisseph as swe
from datetime import datetime
import pytz

zodiac_mapping = {
    "Capricorn": "摩羯座",
    "Aquarius": "水瓶座",
    "Pisces": "双鱼座",
    "Aries": "白羊座",
    "Taurus": "金牛座",
    "Gemini": "双子座",
    "Cancer": "巨蟹座",
    "Leo": "狮子座",
    "Virgo": "处女座",
    "Libra": "天秤座",
    "Scorpio": "天蝎座",
    "Sagittarius": "射手座"
}


def translate_zodiac_to_chinese(english_name):
    """
    将英文星座名翻译成中文。

    参数:
    - english_name: 星座的英文名称

    返回:
    - 对应的中文星座名称
    """
    return zodiac_mapping.get(english_name, "未知星座")


def birthday_to_astro(birthday_str):
    month = int(birthday_str[4:6])
    day = int(birthday_str[6:])

    zodiac_signs = [
        ((1, 19), "Capricorn"), ((1, 20), "Aquarius"), ((2, 18), "Pisces"),
        ((3, 20), "Aries"), ((4, 19), "Taurus"), ((5, 20), "Gemini"),
        ((6, 20), "Cancer"), ((7, 22), "Leo"), ((8, 22), "Virgo"),
        ((9, 22), "Libra"), ((10, 22), "Scorpio"), ((11, 21), "Sagittarius"),
        ((12, 21), "Capricorn")
    ]

    # 默认设置为Capricorn，处理12月的情况
    sign = "Capricorn"
    for (m, d), s in zodiac_signs:
        if (month, day) > (m, d):  # 如果生日大于当前星座的结束日期，则继续循环
            sign = s
        else:  # 否则找到了正确的星座
            break

    return sign

def astro_to_sense(astro):
    astro = astro.lower()
    sense = ""
    match astro:
        case "aries" :
            sense = ARIES_SENSE
        case "taurus" :
            sense = TAURUS_SENSE
        case "gemini" :
            sense = GEMINI_SENSE
        case "cancer" :
            sense = CANCER_SENSE
        case "leo" :
            sense = LEO_SENSE
        case "virgo" :
            sense = VIRGO_SENSE
        case "libra" :
            sense = LIBRA_SENSE
        case "scorpio" :
            sense = SCORPIO_SENSE
        case "sagittarius" :
            sense = SAGITTARIUS_SENSE
        case "capricorn" :
            sense = CAPRICORN_SENSE
        case "aquarius" :
            sense = AQUARIUS_SENSE
        case "pisces" :
            sense = PISCES_SENSE
    return sense

def ruling_planet(constellation_name):
    # 星座与主宰行星的映射字典
    constellation_planet_dict = {
        "aries": "Mars",  # 白羊座 - 火星
        "taurus": "Venus",  # 金牛座 - 金星
        "gemini": "Mercury",  # 双子座 - 水星
        "cancer": "Moon",  # 巨蟹座 - 月亮
        "leo": "Sun",  # 狮子座 - 太阳
        "virgo": "Mercury",  # 处女座 - 水星
        "libra": "Venus",  # 天秤座 - 金星
        "scorpio": "Pluto",  # 天蝎座 - 冥王星（在现代占星学中）
        "sagittarius": "Jupiter",  # 射手座 - 木星
        "capricorn": "Saturn",  # 摩羯座 - 土星
        "aquarius": "Uranus",  # 水瓶座 - 天王星（在现代占星学中）
        "pisces": "Neptune"  # 双鱼座 - 海王星（在现代占星学中）
    }
    # 将输入转换为小写以匹配字典键
    constellation_name = constellation_name.lower()
    if constellation_name in constellation_planet_dict:
        return constellation_planet_dict[constellation_name]
    else:
        return "Unknown"

def get_ruling_planet_birthday_astro(birthday_str:str, ruling_planet_name:str):
    # 加载天文数据
    load = Loader('../raw_data')
    ts = load.timescale()
    eph = load('de421.bsp')  # 这是一个小型的行星历表文件

    # 解析生日字符串
    year = int(birthday_str[0:4])
    month = int(birthday_str[4:6])
    day = int(birthday_str[6:8])
    t = ts.utc(year, month, day)  # 指定日期

    # 计算行星的位置
    if ruling_planet_name.lower() == "sun" or ruling_planet_name.lower() == "moon":
        planet = eph[ruling_planet_name.lower()]
    else:
        planet = eph[ruling_planet_name.lower() + ' barycenter']
    astrometric = eph['earth'].at(t).observe(planet)
    ra, dec, distance = astrometric.radec()

    # 使用 Astropy 转换为 SkyCoord 对象并查找星座
    coord = SkyCoord(ra=ra.hours * u.hourangle, dec=dec.degrees * u.deg)
    constellation = coord.get_constellation()
    return constellation

def get_ruling_planet_zodiac(ruling_planet_name:str, **kwargs):
    # 设置时区和时间
    timezone = pytz.timezone('Asia/Shanghai')  # 根据需要更改时区
    dt = datetime.now(tz=timezone)
    # dt = datetime(2025, 2, 19, 10, 33, tzinfo=timezone)# 当前时间或指定时间
    for key, value in kwargs.items():
        if key == "birthday_str":
            dt = datetime.strptime(value, '%Y%m%d')


    # 初始化瑞士星历表
    swe.set_ephe_path(None)  # 使用默认路径

    # 转换为Julian日
    julian_day = swe.julday(dt.year, dt.month, dt.day, dt.hour + dt.minute / 60.0)

    # 获取地理坐标（例如北京）
    lat, lon, alt = 39.9042, 116.4074, 0  # 北京的经纬度

    # 计算宫位
    houses, ascmc = swe.houses(julian_day, lat, lon, b'P')  # 'P'表示Placidus分宫制

    # 计算位置
    attribute_name = ruling_planet_name.upper()
    planet = getattr(swe, attribute_name)
    mercury_pos = swe.calc_ut(julian_day, planet)[0]
    mercury_long = mercury_pos[0]  # 黄经

    # 找到所在的宫位
    house_index = -1
    for i in range(12):
        if i == 11:
            house_index = 12
            break
        else:
            if houses[i] <= mercury_long < houses[(i + 1) % 12]:
                house_index = i + 1
                break

    # 清理资源
    swe.close()

    num_words = {
        1: 'one', 2: 'two', 3: 'three', 4: 'four',
        5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine',
        10: 'ten', 11: 'eleven', 12: 'twelve'
    }
    logging.info(f"house_index: {house_index}")

    # 返回对应的英文单词
    return num_words[house_index]